/**
 * 最简单的基于FFmpeg的推流器（推送RTMP）
 * Simplest FFmpeg Streamer (Send RTMP)
 *
 * 雷霄骅 Lei Xiaohua
 * leixiaohua1020@126.com
 * 中国传媒大学/数字电视技术
 * Communication University of China / Digital TV Technology
 * http://blog.csdn.net/leixiaohua1020
 *
 * 本例子实现了推送本地视频至流媒体服务器（以RTMP为例）。
 * 是使用FFmpeg进行流媒体推送最简单的教程。
 *
 * This example stream local media files to streaming media
 * server (Use RTMP as example).
 * It's the simplest FFmpeg streamer.
 *
 */

#include <stdio.h>

#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#include <libavutil/opt.h>
#include <libavutil/dict.h>
#include <libavutil/time.h>

#define AUDIO_G711A 1

int main(int argc, char* argv[])
{
    AVOutputFormat *ofmt = NULL;
    //Input AVFormatContext and Output AVFormatContext
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    AVFormatContext *afmt_ctx = NULL;//audio-input AVFormatContex
    AVPacket pkt, apkt;
    AVBSFContext *bsf_ctx = NULL;
    const char *in_filename, *out_filename,*audio_filename;
    int ret, i;
    int videoindex=-1;
    int frame_index=0, audio_index = 0;
    int64_t start_time=0;
    //in_filename  = "cuc_ieschool.mov";
    //in_filename  = "cuc_ieschool.mkv";
    //in_filename  = "cuc_ieschool.ts";
    //in_filename  = "cuc_ieschool.mp4";
    //in_filename  = "cuc_ieschool.h264";
    //in_filename  = "cuc_ieschool.flv";//输入URL（Input file URL）
    //in_filename  = "demo.flv";//输入URL（Input file URL）
    in_filename  = "data/video.h264";
    //audio_filename = "data/audio.aac"; // vlc: stereo, 16000HZ, 32bits
    //audio_filename = "test.aac"; // vlc: stereo, 44100HZ, 32bits
    audio_filename = "data/test.g711a"; // mono, 8000HZ, 16bits

    #if AUDIO_G711A
    FILE *fp = fopen(audio_filename,"rb");
    if(!fp)
    {
	printf("fopen audio file %s fail!\n",audio_filename);
	exit(EXIT_FAILURE);
    }
    #endif

    //out_filename = "rtmp://localhost/publishlive/livestream";//输出 URL（Output URL）[RTMP]
    out_filename = "rtmp://www.wmatrix.net/ipc/ffmpeg";//输出 URL（Output URL）[RTMP]
    //out_filename = "rtp://233.233.233.233:6666";//输出 URL（Output URL）[UDP]

    av_register_all();
    //Network
    avformat_network_init();
    //Input
    if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
	printf( "Could not open input file.\n");
	goto end;
    }
    if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
	printf( "Failed to retrieve input stream information\n");
	goto end;
    }

    for(i=0; i<ifmt_ctx->nb_streams; i++)
    {
	//if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
	if(ifmt_ctx->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_VIDEO){
	    videoindex=i;
	    //break;
	}
	else
	{
	    AVStream *audio_stream = ifmt_ctx->streams[i];
	    printf("Audio CodecParameters: chnlayout = %ld,channels = %d,sample_rate = %d\n",audio_stream->codecpar->channel_layout,
		audio_stream->codecpar->channels,audio_stream->codecpar->sample_rate);
	}
    }

    ifmt_ctx->streams[0]->time_base.num = 1;
    ifmt_ctx->streams[0]->time_base.den = 1000;
    av_dump_format(ifmt_ctx, 0, in_filename, 0);

    if(ifmt_ctx->nb_streams == 1)
    {//add audio input
	AVDictionary *options = NULL;
#if AUDIO_G711A
	//nothing;
#else
	av_dict_set(&options,"channel_layout","3",0);
	av_dict_set(&options,"bits_per_raw_sample","32",0);
	av_dict_set(&options,"ar","44100",0);
	av_dict_set(&options,"ac","2",0);

	if ((ret = avformat_open_input(&afmt_ctx, audio_filename, 0, &options)) < 0) {
	    printf( "Could not open audio input file:%s\n",audio_filename);
	    av_dict_free(&options);
	    goto end;
	}
	AVDictionaryEntry *e = NULL;
	if(e=av_dict_get(options,"",NULL,AV_DICT_IGNORE_SUFFIX))
	{
	    printf("Options %s are unrecognized by demuxer!\n",e->key);
	}
	av_dict_free(&options);

	AVStream *audio_stream = afmt_ctx->streams[0];
#if 1
	if ((ret = avformat_find_stream_info(afmt_ctx, 0)) < 0) {
	    printf( "Failed to retrieve input stream information\n");
	    av_dict_free(&options);
	    goto end;
	}
#else
	printf("audio streams num = %d\n",afmt_ctx->nb_streams);
	audio_stream->codecpar->channel_layout = 3;
	audio_stream->codecpar->channels = 2;
	audio_stream->codecpar->sample_rate = 16000;
	//audio_stream->codecpar->sample_rate = 44100;
	audio_stream->codecpar->bits_per_coded_sample = 32;
	audio_stream->codecpar->bits_per_raw_sample = 32;
	audio_stream->codecpar->format = AV_SAMPLE_FMT_FLTP;
	audio_stream->codecpar->profile = 1;
	audio_stream->codecpar->level = -99;
	afmt_ctx->streams[0]->time_base.num = 1;
	afmt_ctx->streams[0]->time_base.den = 1000;
#endif
	AVCodecParameters *audio_params = audio_stream->codecpar;
	printf("Audio CodecParameters: chnlayout = %ld,channels = %d,sample_rate = %d,profile = %d,level = %d,bits_per_raw_sample = %d\n",
		audio_params->channel_layout, audio_params->channels,audio_params->sample_rate,
		audio_params->profile,audio_params->level,audio_params->bits_per_raw_sample);

	av_dump_format(afmt_ctx, 0, audio_filename, 0);
#endif
    }

    //Output
    char errbuf[1024]={0};
    avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_filename); //RTMP
    //avformat_alloc_output_context2(&ofmt_ctx, NULL, "mpegts", out_filename);//UDP
    //ret = av_opt_set_int(ofmt_ctx,"rtmp_live",1,AV_OPT_SEARCH_CHILDREN);
    //if(ret < 0) av_strerror(ret,errbuf,sizeof(errbuf));
    //printf("av opt set rtmp_live ret = %d,err: %s\n",ret,errbuf);

    if (!ofmt_ctx) {
	printf( "Could not create output context\n");
	ret = AVERROR_UNKNOWN;
	goto end;
    }
    ofmt = ofmt_ctx->oformat;
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
	//Create output AVStream according to input AVStream
	AVStream *in_stream = ifmt_ctx->streams[i];
	//AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
	AVStream *out_stream = avformat_new_stream(ofmt_ctx, avcodec_find_encoder(in_stream->codecpar->codec_id));
	if (!out_stream) {
	    printf( "Failed allocating output stream\n");
	    ret = AVERROR_UNKNOWN;
	    goto end;
	}
	//Copy the settings of AVCodecContext
	//ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
	ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
	if (ret < 0) {
	    printf( "Failed to copy context from input to output stream codec context\n");
	    goto end;
	}
	//out_stream->codec->codec_tag = 0;
	out_stream->codecpar->codec_tag = 0;
	//if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
	//    out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }

    if(ofmt_ctx->nb_streams==1)
    {
#if AUDIO_G711A
	AVStream *out_stream = avformat_new_stream(ofmt_ctx, avcodec_find_encoder(AV_CODEC_ID_PCM_ALAW));
	if (!out_stream) {
	    printf( "Failed allocating output stream\n");
	    ret = AVERROR_UNKNOWN;
	    goto end;
	}
	printf("out audio stream = %p,codecpar = %p\n",out_stream,out_stream->codecpar);
	AVCodecParameters *audio_codecpar = out_stream->codecpar;
	audio_codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
	audio_codecpar->codec_id = AV_CODEC_ID_PCM_ALAW;
	audio_codecpar->codec_tag = 0;
	audio_codecpar->channel_layout = 4;
	audio_codecpar->channels = 1;
	audio_codecpar->sample_rate = 8000;
	audio_codecpar->bits_per_coded_sample = 16;
	audio_codecpar->bits_per_raw_sample = 16;
	audio_codecpar->format = AV_SAMPLE_FMT_S16;
	out_stream->time_base.num = 1;
	out_stream->time_base.den = 1000;

	out_stream->codecpar->codec_tag = 0;
#else
	AVStream *in_stream = afmt_ctx->streams[0];
	AVStream *out_stream = avformat_new_stream(ofmt_ctx, avcodec_find_encoder(in_stream->codecpar->codec_id));
	if (!out_stream) {
	    printf( "Failed allocating output stream\n");
	    ret = AVERROR_UNKNOWN;
	    goto end;
	}
	//Copy the settings of AVCodecParameters
	ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
	if (ret < 0) {
	    printf( "Failed to copy context from input to output stream codec context\n");
	    goto end;
	}
	//out_stream->codecpar->codec_tag = 0;
	out_stream->codecpar->codec_tag = 0;
	//if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
	//   out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
#endif
    }

    //Dump Format------------------
    av_dump_format(ofmt_ctx, 0, out_filename, 1);
    //Open output URL
    if (!(ofmt->flags & AVFMT_NOFILE)) {
	ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
	if (ret < 0) {
	    printf( "Could not open output URL '%s'", out_filename);
	    goto end;
	}
    }
    //Write file header
    ret = avformat_write_header(ofmt_ctx, NULL);
    if (ret < 0) {
	printf( "Error occurred when opening output URL\n");
	goto end;
    }

    int audio_flag = 0;
    int audio_end = 0;
    const AVBitStreamFilter *filter = av_bsf_get_by_name("aac_adtstoasc");
    if(!filter)
    {
	av_log(NULL,AV_LOG_ERROR,"Unkonw bitstream filter");
	goto end;
    }
    ret = av_bsf_alloc(filter, &bsf_ctx);
    if(ret < 0)
    {
	av_log(NULL,AV_LOG_ERROR,"alloc bitstream filter failed!");
	goto end;
    }

    char pcmaBuf[640]={0};
    int pcmaSize = 0;
    start_time=av_gettime();
    while (1)
    {
	AVStream *in_stream, *out_stream;
	//Get an AVPacket
	if(audio_flag && !audio_end && ifmt_ctx->nb_streams==1)
	{//Need Filter
	    #if AUDIO_G711A
	    pcmaSize = fread(pcmaBuf,1,320,fp);
	    if(pcmaSize != 320)
	    {
		rewind(fp);
		pcmaSize = fread(pcmaBuf,1,320,fp);
	    }
	    //printf("G711 Size = %d\n",pcmaSize);
	    uint8_t *pdata = (uint8_t*)av_malloc(pcmaSize);
	    memcpy(pdata,pcmaBuf,pcmaSize);
	    ret = av_packet_from_data(&pkt,pdata,pcmaSize);
	    if(ret < 0)
	    {
		printf("av_packet_from_data fail,ret = %d\n",ret);
		av_free(pdata);
		continue;
	    }
	    pkt.pts = AV_NOPTS_VALUE;//reset it!
	    pkt.stream_index = 1;
	    #else
	    if(afmt_ctx!=NULL)
	    {
		ret = av_read_frame(afmt_ctx,&pkt);
		//printf("read audio ret = %d,pkt size = %d,pts = %ld\n",ret,pkt.size,pkt.pts);
		if(ret < 0)
		{
		    printf("read audio ret = %d,it's end!\n",ret);
		    audio_end = 1;
		    continue;
		}
		pkt.pts = AV_NOPTS_VALUE;//reset it!
		pkt.stream_index = 1; // Audio Stream
	    }
	    #endif
	}
	else
	{
	    //printf("---read video frame...\n");
	    ret = av_read_frame(ifmt_ctx, &pkt);
	    if (ret < 0)
		break;
	    //printf("---read video frame...ret = %d\n",ret);
	}

	//FIX：No PTS (Example: Raw H.264)
	//Simple Write PTS
	if(pkt.pts==AV_NOPTS_VALUE){
	    //Write PTS
	    AVRational time_base1=ifmt_ctx->streams[videoindex]->time_base;
	    //Duration between 2 frames (us)
	    int64_t calc_duration=(double)AV_TIME_BASE/av_q2d(ifmt_ctx->streams[videoindex]->r_frame_rate);
	    #if AUDIO_G711A
	    //if(audio_flag)
	    //{
	    //    calc_duration = 20*1000;//us
	    //    pkt.pts=(double)(audio_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);
	    //}
	    //else
	    //{
	    //    pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);
	    //}
	    #else
	    pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);
	    #endif
	    pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);
	    //Parameters,unit : stream->time_base
	    pkt.dts=pkt.pts;
	    pkt.duration=(double)calc_duration/(double)(av_q2d(time_base1)*AV_TIME_BASE);
	}
	//Important:Delay
	if(pkt.stream_index==videoindex){
	    AVRational time_base=ifmt_ctx->streams[videoindex]->time_base;
	    AVRational time_base_q={1,AV_TIME_BASE};
	    int64_t pts_time = av_rescale_q(pkt.dts, time_base, time_base_q);
	    int64_t now_time = av_gettime() - start_time;
	    if (pts_time > now_time)
		av_usleep(pts_time - now_time);
	}

	//printf("-----calc pts/dts end ...\n");

	if(audio_flag)
	{
	    #if AUDIO_G711A
	    //unused...
	    #else
	    in_stream  = afmt_ctx->streams[pkt.stream_index];
	    #endif
	}
	else
	{
	    in_stream  = ifmt_ctx->streams[pkt.stream_index];
	}
	out_stream = ofmt_ctx->streams[pkt.stream_index];
	/* copy packet */
	//Convert PTS/DTS
	//printf("-----convert pts/dts begin...\n");
	AVRational video_time_base=ifmt_ctx->streams[videoindex]->time_base;
	pkt.pts = av_rescale_q_rnd(pkt.pts, video_time_base/*in_stream->time_base*/, out_stream->time_base, (enum AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
	pkt.dts = av_rescale_q_rnd(pkt.dts, video_time_base/*in_stream->time_base*/, out_stream->time_base, (enum AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
	pkt.duration = av_rescale_q(pkt.duration, video_time_base/*in_stream->time_base*/, out_stream->time_base);
	pkt.pos = -1;
	//printf("-----convert pts/dts end...\n");
	//Print to Screen
	if(pkt.stream_index==videoindex){
	    //printf("Send %8d video frames to output URL\n",frame_index);
	    frame_index++;
	    if(ifmt_ctx->nb_streams==1) { audio_flag = 1; }
	}
	else if(audio_flag) {
	    audio_index++;
	    #if AUDIO_G711A
	    //if(audio_index%2) audio_flag = 0;// 2 frames = 40ms
	    audio_flag = 0;
	    #else
	    audio_flag = 0;
	    #endif
	}

	//printf("-----write frame begin...\n");

	if(pkt.stream_index == 1)
	{
	    #if AUDIO_G711A
	    //printf("audio packet pts = %ld,duration = %ld,size = %d\n",pkt.pts,pkt.duration,pkt.size);
	    ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
	    if (ret < 0) {
		printf( "Error muxing packet\n");
		av_packet_unref(&pkt);
		break;
	    }
	    //printf("av write audio frame ret = %d\n",ret);
	    #else
	    ret = av_bsf_send_packet(bsf_ctx,&pkt);
	    if(ret < 0)
	    {
		av_log(NULL,AV_LOG_ERROR,"send packet to filter failed!");
		break;
	    }
	    int cnt = 0;
	    while((ret = av_bsf_receive_packet(bsf_ctx,&apkt))==0)
	    {
		//printf("[%d]audio packet pts = %ld,duration = %ld,size = %d\n",cnt++,apkt.pts,apkt.duration,apkt.size);
		ret = av_interleaved_write_frame(ofmt_ctx, &apkt);
		if (ret < 0) {
		    printf( "Error muxing packet\n");
		    av_packet_unref(&apkt);
		    break;
		}
		av_packet_unref(&apkt);
	    }
	    #endif
	}
	else
	{
	    //printf("packet pts = %ld,duration = %ld,size = %d,data = %p\n", pkt.pts,pkt.duration,pkt.size,pkt.data);
	    //ret = av_write_frame(ofmt_ctx, &pkt);
	    ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
	    if (ret < 0) {
		printf( "Error muxing packet\n");
		av_packet_unref(&pkt);
		break;
	    }
	    //printf("av write video frame ret = %d\n",ret);
	}
	//av_free_packet(&pkt);
	av_packet_unref(&pkt);
    }

    printf("Send %8d video frames to output URL...End!\n",frame_index);
    //Write file trailer
    av_write_trailer(ofmt_ctx);

end:
    printf("end...start\n");
    if(bsf_ctx) av_bsf_free(&bsf_ctx);

    if(ifmt_ctx)
	avformat_close_input(&ifmt_ctx);
    if(afmt_ctx)
    {
	avformat_close_input(&afmt_ctx);
    }
    #if AUDIO_G711A
    if(fp) fclose(fp);
    #endif

    /* close output */
    if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
	avio_close(ofmt_ctx->pb);
    if(ofmt_ctx) avformat_free_context(ofmt_ctx);
    if (ret < 0 && ret != AVERROR_EOF) {
	printf( "Error occurred.\n");
	return -1;
    }
    return 0;
}

